package com.guoqi.clickevent

import android.app.Application
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Point
import android.os.Build
import android.text.TextUtils
import android.util.DisplayMetrics
import android.view.KeyCharacterMap
import android.view.KeyEvent
import android.view.ViewConfiguration
import android.view.WindowManager
import android.widget.Toast

object SystemUtils {
    private var screenHeight = 0
    private val screenWidth = 0
    private var statusBarHeight = 0

    /**
     * 获取屏幕宽度
     */
    @JvmStatic
    fun getScreenWidth(mContext: Context?): Int {
        return if (screenWidth > 0) {
            screenWidth
        } else mContext?.resources?.displayMetrics?.widthPixels ?: 0

    }

//    fun getScreenWidth(context: Context): Int {
//        val metric = DisplayMetrics()
//        val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
//        wm.defaultDisplay.getMetrics(metric)
//        return metric.widthPixels
//    }

    /**
     * 获取屏幕高度,是否包含导航栏高度
     */
    @JvmStatic
    fun getScreenHeight(mContext: Context?, isIncludeNav: Boolean): Int {
        if (mContext == null) {
            return 0
        }
        val screenHeight = getScreenHeight(mContext)
        return if (isIncludeNav) {
            screenHeight
        } else {
            screenHeight - getNavigationBarHeight(mContext)
        }
    }

    /**
     * 获取屏幕高(包括底部虚拟按键)
     *
     * @param mContext
     * @return
     */
    @JvmStatic
    fun getScreenHeight(mContext: Context?): Int {
        if (screenHeight > 0) {
            return screenHeight
        }

        if (mContext == null) {
            return 0
        }
        val displayMetrics = DisplayMetrics()
        //WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        val display = getWindowManager(mContext)!!.defaultDisplay
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                display.getRealMetrics(displayMetrics)
            } else {
                display.getMetrics(displayMetrics)
            }
            screenHeight = displayMetrics.heightPixels
        } catch (e: Exception) {
            screenHeight = display.height
        }

        return screenHeight
    }

    /**
     * 获取WindowManager。
     */
    @JvmStatic
    fun getWindowManager(mContext: Context?): WindowManager? {
        return if (mContext == null) {
            null
        } else mContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    }
//    fun getScreenHeight(context: Context): Int {
//        val metric = DisplayMetrics()
//        val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
//        wm.defaultDisplay.getMetrics(metric)
//        return metric.heightPixels
//    }

    /**
     * 获取NavigationBar的高度
     */
    fun getNavigationBarHeight(mContext: Context): Int {
        if (!hasNavigationBar(mContext)) {
            return 0
        }
        val resources = mContext.resources
        val resourceId = resources.getIdentifier("navigation_bar_height",
                "dimen", "android")
        return resources.getDimensionPixelSize(resourceId)
    }

    /**
     * 是否存在NavigationBar
     */
    fun hasNavigationBar(mContext: Context): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            val display = getWindowManager(mContext)!!.defaultDisplay
            val size = Point()
            val realSize = Point()
            display.getSize(size)
            display.getRealSize(realSize)
            return realSize.x != size.x || realSize.y != size.y
        } else {
            val menu = ViewConfiguration.get(mContext).hasPermanentMenuKey()
            val back = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK)
            return !(menu || back)
        }
    }

    /**
     * 将px值转换为dip或dp值，保证尺寸大小不变
     */
    @JvmStatic
    fun px2dp(context: Context, pxValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (pxValue / scale + 0.5f).toInt()
    }

    /**
     * 将dip或dp值转换为px值，保证尺寸大小不变
     */
    @JvmStatic
    fun dp2px(context: Context, dipValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (dipValue * scale + 0.5f).toInt()
    }


    private fun getStatusBarHeightByReflect(mContext: Context): Int {
        //int sbHeight;
        if (statusBarHeight > 0) {
            return statusBarHeight
        }
        try {
            val c = Class.forName("com.android.internal.R\$dimen")
            val obj = c.newInstance()
            val field = c.getField("status_bar_height")
            val sbHeightId = Integer.parseInt(field.get(obj).toString())
            statusBarHeight = mContext.resources.getDimensionPixelSize(sbHeightId)
        } catch (e1: java.lang.Exception) {
            e1.printStackTrace()
            statusBarHeight = 0
        }

        return statusBarHeight
    }

    @JvmStatic
    fun getStatusBarHeight(mContext: Context): Int {
        var statusBarHeight = getStatusBarHeightByReflect(mContext)
        if (statusBarHeight == 0) {
            statusBarHeight = dp2px(mContext, 30f)
        }
        return statusBarHeight
    }

    /**
     * 是否已安装
     */
    private fun isApkInstalled(context: Context, packageName: String): Boolean {
        if (TextUtils.isEmpty(packageName)) {
            return false
        }
        return try {
            val info = context.packageManager.getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES)
            true
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            false
        }
    }

    @JvmStatic
    open fun openApp(application: Application) {
        if (isApkInstalled(application, ClickService.targetPackageName)) {
            //Toast.makeText(application, "正在打开[${ClickService.targetPackageName}]", Toast.LENGTH_LONG).show()
            val intent = application.packageManager.getLaunchIntentForPackage(ClickService.targetPackageName)
            if (intent != null) {
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                application.startActivity(intent)

//                Handler().postDelayed({
//                    val intent = Intent("qukan_auto_browser")
//                    application.sendBroadcast(intent)
//                }, 0)
            }

        } else {
            Toast.makeText(application, "未安装${ClickService.targetPackageName}", Toast.LENGTH_LONG).show()
        }
    }
}
